package keye.document_manage.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.JButton;

import java.awt.CardLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.StampedLock;

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.BoxLayout;

import keye.document_manage.util.FileUtil;


public class ProgressFrame extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int rowHeight = 30;//行高度
	private JPanel contentPane;
	private JTable table;
	private JTable table_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ProgressFrame frame = new ProgressFrame();
					frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ProgressFrame() {
		setIconImage(null);
		setTitle("");
		init("展示1","展示2",new String[]{"门类", "进度", "操作"},new String[]{"门类","用时", "操作"});
	}
	
	/**
	 * 
	 * @param title 窗口标题
	 * @param tableTitle 第一个面板标题
	 * @param table2Tittle 第二个面板标题
	 * @param tableCol 第一个表格的列名
	 * @param table2Col 第二个表格的列名
	 */
	public ProgressFrame(String title,String tableTitle, String table2Tittle, String[] tableCol,String[] table2Col) {
		setIconImage(null);
		setTitle(title);
		init(tableTitle, table2Tittle, tableCol, table2Col);
	}

	@SuppressWarnings("serial")
	protected void init(String tableTitle, String table2Tittle, String[] tableCol,String[] table2Col){
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 324, 400);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		CardLayout card = new CardLayout(0,0);
		panel.setLayout(card);

		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
		panel.add(scrollPane, "one");

		table = new JTable();
		table.setRowHeight(rowHeight);
		table.setDefaultRenderer(Object.class, new MyTableCellRenderer());
		table.setModel(new DefaultTableModel(
				new Object[][] {
//						{"1","2",new JButton("暂停")},{"1","2",new JButton("暂停")},{"1","2",new JButton("暂停")},
				},
				tableCol
				){
				Class<?>[] columnTypes = new Class[] {
					String.class, String.class, Object.class
				};
				public Class<?> getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
			
			public boolean isCellEditable(int row, int column) {
				return false;
			};
			@Override
			public Object getValueAt(int row, int column) {
				if(column!=2)
					return super.getValueAt(row, column);
				else{
					final JButton button = new JButton("");
					button.addActionListener(e->{System.out.println(row+" "+column);});
					return button;
				}
			}
		});
		TableCellRenderer buttonRenderer = new JTableButtonRenderer();
		table.getColumn(tableCol[2]).setCellRenderer(buttonRenderer);
		table.addMouseListener(new JTableButtonMouseListener(table));
		modeCheck = (DefaultTableModel)table.getModel();
		table.getTableHeader().setReorderingAllowed(false);
		scrollPane.setViewportView(table);

		JScrollPane scrollPane_1 = new JScrollPane();
		panel.add(scrollPane_1, "two");

		table_1 = new JTable();
		table_1.setRowHeight(rowHeight);
		table_1.setDefaultRenderer(Object.class, new MyTableCellRenderer());
		table_1.getTableHeader().setReorderingAllowed(false);
		table_1.setModel(new DefaultTableModel(
				new Object[][] {
//						{"1","2","M:\\test\\log.txt"},{"1","2",}
				},
				table2Col
				){
			Class<?>[] columnTypes = new Class[] {
					String.class, String.class, JButton.class
				};
				public Class<?> getColumnClass(int columnIndex) {
					return columnTypes[columnIndex];
				}
			
			public boolean isCellEditable(int row, int column) {
				return false;
			};
			@Override
			public Object getValueAt(int row, int column) {
				if(column!=2)
					return super.getValueAt(row, column);
				else{
					String path = (String) super.getValueAt(row, column);
					final JButton button = new JButton("查看");
					if(path!=null){
						if(Files.isDirectory(Paths.get(path)))
							button.addActionListener(e->FileUtil.openDirectory(path));
						else
							button.addActionListener(e->FileUtil.openTxt(path));
					}
					return button;
				}
			}
		});
//		TableCellRenderer buttonRenderer2 = new JTableButtonRenderer();
		table_1.getColumn(table2Col[2]).setCellRenderer(buttonRenderer);
		table_1.addMouseListener(new JTableButtonMouseListener(table_1));
		modeComplete = (DefaultTableModel)table_1.getModel();
		table_1.getTableHeader().setReorderingAllowed(false);
		scrollPane_1.setViewportView(table_1);

		JPanel panel_1 = new JPanel();
		contentPane.add(panel_1, BorderLayout.NORTH);
		panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.X_AXIS));

		JButton button = new JButton(tableTitle);
		panel_1.add(button);
		button.addActionListener(e->card.show(panel, "one"));

		JButton button_1 = new JButton(table2Tittle);
		panel_1.add(button_1);
		button_1.addActionListener(e->card.show(panel, "two"));
		
		this.setVisible(false);
	}
	DefaultTableModel modeCheck, modeComplete;
	
	public synchronized int addOneCheck(String name, String progress){
		modeCheck.addRow(new Object[]{name,progress,""});
		size++;
		int row = size-1;
		//每增加一行，保存这一行（key）和这行的下标（value）
		rowMap.put(row, row);
		return row;
	}

	public void addOneComplete(String name,String time,String logPath){
		modeComplete.addRow(new Object[]{name,time,logPath});
	}
	
	public void updateProgressCheck(String v, int row,int col){
		if(row < 0 || row>=size)
			return;
		modeCheck.setValueAt(v, row, col);
	}
	
	private int size=0;
	
	private Map<Integer,Integer> rowMap = new HashMap<Integer, Integer>();
	
	private final StampedLock sl = new StampedLock(); 
	
	public  void removeOneCheck(int index){
		long stamp = sl.writeLock();  
		try {  
			Thread.sleep(300);
			int row  = rowMap.get(index);
			System.out.println(index+": "+row);
			modeCheck.removeRow(row);
			rowMap.remove(index);
			//移除一行的时候，在这行后面的每一行的下标都会减 1，
			rowMap.keySet().stream().filter(k->k>row).forEach(key->{
				int v = rowMap.get(key);
				if(v>0)
					rowMap.replace(key, v-1);
				});
			size--;
		}catch(Exception e){
			e.printStackTrace();
		} 
		finally {  
			sl.unlockWrite(stamp);  
		}  
	}

	public int getRowCheck(int key){
		return rowMap.get(key);
	}
	
	public JTable getCheckingTable(){
		return this.table;
	}
	
	public int getLastIndex(){
		return modeCheck.getRowCount();
	}

}

class JTableButtonRenderer implements TableCellRenderer {		
	@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
		JButton button = (JButton)value;
		if (isSelected) {
			button.setForeground(table.getSelectionForeground());
			button.setBackground(table.getSelectionBackground());
	    } else {
	    	button.setForeground(table.getForeground());
	    	button.setBackground(UIManager.getColor("Button.background"));
	    }
		return button;	
	}
}

class JTableButtonMouseListener extends MouseAdapter {
	private final JTable table;
	
	public JTableButtonMouseListener(JTable table) {
		this.table = table;
	}

	public void mouseClicked(MouseEvent e) {
		int column = table.getColumnModel().getColumnIndexAtX(e.getX());
		int row    = e.getY()/table.getRowHeight(); 

		if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
		    Object value = table.getValueAt(row, column);
		    if (value instanceof JButton) {
		    	((JButton)value).doClick();
		    }
		}
	}
}